<template>
    <div class="exam-container">
        <el-affix :offset="0">
            <el-card class="exam-header" shadow="never">
                <div class="header-content">
                    <div class="exam-title">
                        <h3>{{ currentExam?.title || '加载中...' }}</h3>
                        <p>总分: 100分 | 题目总数: {{ totalQuestionCount }}</p>
                    </div>
                    <div class="exam-timer">
                        <el-tag type="danger" size="large" effect="dark">
                            <span>剩余时间: {{ formattedTime }}</span>
                        </el-tag>
                    </div>
                    <div class="answer-sheet">
                        <div class="sheet-title">答题卡</div>
                        <div class="sheet-progress">
                            <span>当前进度: {{ answeredCount }} / {{ totalQuestionCount }}</span>
                        </div>
                        <div class="sheet-numbers">
                            <a v-for="q in sortedQuestions" :key="q.examQuestion.id"
                                :href="'#question-' + q.examQuestion.id" class="sheet-number"
                                :class="{ 'answered': studentAnswers[q.examQuestion.id] }">
                                {{ q.examQuestion.sequence }}
                            </a>
                        </div>
                    </div>
                </div>
            </el-card>
        </el-affix>
        <div class="p-4 pt-3">
            <el-card class="box-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <strong>考核说明</strong>
                    </div>
                </template>
                <div v-if="currentExam?.description" class="description-content">
                    {{ currentExam.description }}
                </div>
                <div v-else class="text-muted">
                    暂无考核说明。
                </div>
            </el-card>
        </div>

        <div class="question-list-container p-4 pt-0">
            <div v-if="loading" class="text-center p-5">加载中...</div>

            <template v-if="!isSubmitted">
                <el-card v-for="question in sortedQuestions" :key="question.examQuestion.id" class="question-card"
                    :id="'question-' + question.examQuestion.id">
                    <template #header>
                        <div class="question-title">
                            <strong>{{ question.examQuestion.sequence }}.【{{
                                getQuestionTypeName(question.examQuestion.questionType) }} | {{
                                    question.examQuestion.points }}分】</strong>
                        </div>
                    </template>
                    <div class="question-content">
                        <p class="mb-3">{{ question.examQuestion.content }}</p>
                        <el-radio-group
                            v-if="question.examQuestion.questionType === 'single_choice' || question.examQuestion.questionType === 'true_false'"
                            v-model="studentAnswers[question.examQuestion.id]">
                            <el-radio v-for="option in question.options" :key="option.id" :value="option.id"
                                size="large" border class="d-block mb-2">
                                {{ getOptionLabel(option.sequence) }}. {{ option.optionContent }}
                            </el-radio>
                        </el-radio-group>
                        <el-checkbox-group v-if="question.examQuestion.questionType === 'multi_choice'"
                            v-model="studentAnswers[question.examQuestion.id]">
                            <el-checkbox v-for="option in question.options" :key="option.id" :value="option.id"
                                size="large" border class="d-block mb-2">
                                {{ getOptionLabel(option.sequence) }}. {{ option.optionContent }}
                            </el-checkbox>
                        </el-checkbox-group>
                        <el-input
                            v-if="['fill_blank', 'short_answer', 'essay'].includes(question.examQuestion.questionType)"
                            v-model="studentAnswers[question.examQuestion.id]" type="textarea" :rows="4"
                            placeholder="请输入你的答案..."></el-input>
                    </div>
                </el-card>

                <div class="submit-footer text-center mt-4">
                    <el-button type="success" size="large" @click="confirmSubmit" :loading="isSubmitting">
                        提 交 答 卷
                    </el-button>
                </div>
            </template>

            <template v-else>
                <div class="results-summary mb-4 p-3 bg-light border rounded">
                    <h4>作答结果</h4>
                    <p>客观题已自动批改，主观题部分待教师审阅。</p>
                </div>
                <el-card v-for="result in submissionResult" :key="result.examQuestion.id" class="question-card">
                    <template #header>
                        <div class="d-flex justify-content-between">
                            <strong>{{ result.examQuestion.sequence }}.【{{
                                getQuestionTypeName(result.examQuestion.questionType) }} | {{ result.examQuestion.points
                                }}分】</strong>
                            <el-tag v-if="result.studentAnswer"
                                :type="getScoreTagType(result.studentAnswer, result.examQuestion)">
                                得分: {{ result.studentAnswer.score ?? '待批改' }}
                            </el-tag>
                        </div>
                    </template>
                    <p class="mb-3">{{ result.examQuestion.content }}</p>

                    <!-- <div class="answer-box">
                        <div class="answer-row">
                            <el-tag type="info" class="answer-tag">你的答案</el-tag>
                            <span class="answer-content student-answer">{{ result.studentAnswer?.content || '未作答'
                                }}</span>
                        </div>
                        <div class="answer-row"
                            v-if="['single_choice', 'multi_choice', 'true_false'].includes(result.examQuestion.questionType)">
                            <el-tag type="success" class="answer-tag">标准答案</el-tag>
                            <span class="answer-content">{{ result.examQuestion.referenceAnswer }}</span>
                        </div>
                    </div> -->
                    <div class="answer-box">
                        <div class="answer-row">
                            <el-tag type="info" class="answer-tag">你的答案</el-tag>
                            <span class="answer-content student-answer">{{ result.studentAnswer?.content || '未作答'
                            }}</span>
                        </div>
                        <div class="answer-row"
                            v-if="['single_choice', 'multi_choice', 'true_false'].includes(result.examQuestion.questionType)">
                            <el-tag type="success" class="answer-tag">标准答案</el-tag>
                            <span class="answer-content">{{ result.examQuestion.referenceAnswer }}</span>
                        </div>
                        <div class="answer-row" v-if="result.studentAnswer?.feedback">
                            <el-tag type="warning" class="answer-tag">AI 评价</el-tag>
                            <span class="answer-content feedback-content">{{ result.studentAnswer.feedback }}</span>
                        </div>
                    </div>
                </el-card>

                <div class="submit-footer text-center mt-4">
                    <el-button type="primary" size="large" @click="router.push('/student/student-assessment-plus')">
                        返 回 列 表
                    </el-button>
                </div>
            </template>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useExamStore } from '@/stores/exam.js';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user.js';
// --- 状态和路由 ---
const route = useRoute();
const router = useRouter();
const examStore = useExamStore();
const userStore = useUserStore();
const { questions, loading, currentExam } = storeToRefs(examStore);
const examId = ref(route.params.examId);
const isSubmitting = ref(false);
// --- 新增：倒计时相关状态 ---
const DEFAULT_DURATION_MINUTES = 90; // <-- 把这一行加回来
let timerId = null;
const remainingSeconds = ref(DEFAULT_DURATION_MINUTES * 60);
// 核心：用于存储学生答案的对象
// 结构: { questionId: answer, ... }
// 例如: { 101: 'A', 102: ['B', 'C'], 103: '学生填写的答案' }
const studentAnswers = reactive({});
// --- 新增：页面状态管理 ---
const isSubmitted = ref(false); // 标志位，判断是否已提交
const submissionResult = ref(null); // 用于存储提交并判分后的结果

// --- 生命周期 ---
onMounted(() => {
    examStore.fetchQuestionsByExamId({ examId: examId.value, pageSize: -1 });
});
onUnmounted(() => {
    if (timerId) {
        clearInterval(timerId);
    }
});
// 监听考核数据，用于解析时长并启动计时器
watch(currentExam, (newExam) => {
    // 确保 newExam 和 newExam.description 存在
    if (newExam && newExam.description) {

        // 使用正则表达式从 description 字段中提取“XX分钟”
        const match = newExam.description.match(/考试时长(\d+)\s*分钟/);

        let durationInMinutes = DEFAULT_DURATION_MINUTES; // 默认时长

        if (match && match[1]) {
            // 如果匹配成功，则使用提取到的数字
            durationInMinutes = parseInt(match[1], 10);
            ElMessage.success(`已设置考试时长为 ${durationInMinutes} 分钟`);
        } else {
            // 如果未找到匹配项，则使用默认时长
            ElMessage.info(`未在考核说明中找到时长，将使用默认的 ${DEFAULT_DURATION_MINUTES} 分钟`);
        }

        // 设置总秒数并启动计时器
        remainingSeconds.value = durationInMinutes * 60;
        startTimer();
    }
}, {
    immediate: true // 如果希望在组件加载时立即执行一次，可以保留或添加此项
});
// --- 计算属性 ---
const sortedQuestions = computed(() => {
    if (!Array.isArray(questions.value)) return [];
    return [...questions.value].sort((a, b) => a.examQuestion.sequence - b.examQuestion.sequence);
});
const formattedTime = computed(() => {
    const hours = Math.floor(remainingSeconds.value / 3600);
    const minutes = Math.floor((remainingSeconds.value % 3600) / 60);
    const seconds = remainingSeconds.value % 60;
    // 使用 padStart 补零，例如 5 -> 05
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
});

// --- 新增：格式化答案以匹配后端API格式 ---
const formatAnswersForSubmission = () => {
    // 遍历完整的、排好序的试题列表，确保每一道题都被包含
    return sortedQuestions.value.map(questionData => {
        const questionId = questionData.examQuestion.id;
        const questionType = questionData.examQuestion.questionType;
        const studentAnswer = studentAnswers[questionId]; // 从学生答案对象中获取对应题目的答案

        let formattedContent = ""; // 默认值设置为空字符串

        // 只有在学生确实作答了的情况下，才进行格式化
        if (studentAnswer) {
            if (questionType === 'single_choice' || questionType === 'true_false') {
                const selectedOption = questionData.options.find(opt => opt.id === studentAnswer);
                if (selectedOption) {
                    formattedContent = getOptionLabel(selectedOption.sequence);
                }
            } else if (questionType === 'multi_choice') {
                if (Array.isArray(studentAnswer) && studentAnswer.length > 0) {
                    const selectedLabels = studentAnswer
                        .map(optionId => {
                            const selectedOption = questionData.options.find(opt => opt.id === optionId);
                            return selectedOption ? getOptionLabel(selectedOption.sequence) : null;
                        })
                        .filter(label => label !== null)
                        .sort();
                    formattedContent = selectedLabels.join(',');
                }
            } else {
                // 对于填空、简答等题型，直接使用学生输入的文本
                // 如果学生输入后又删除了，`studentAnswer` 会是 ""，这里也正确地处理了
                formattedContent = studentAnswer;
            }
        }

        // 返回符合后端格式的对象
        return {
            questionId: questionId,
            content: formattedContent // 如果未作答，这里就是 ""
        };
    });
};

// --- 方法：启动计时器 ---
const startTimer = () => {
    // 先清除可能存在的旧计时器，防止重复启动
    if (timerId) {
        clearInterval(timerId);
    }

    timerId = setInterval(() => {
        if (remainingSeconds.value > 0) {
            remainingSeconds.value--;
        } else {
            // 时间到，停止计时并强制交卷
            clearInterval(timerId);
            ElMessage.warning({
                message: '考试时间到，系统将自动为您提交试卷！',
                duration: 5000,
            });
            submitExam(true); // 调用提交函数，并传入“强制”标记
        }
    }, 1000);
};
const totalQuestionCount = computed(() => sortedQuestions.value.length);

const answeredCount = computed(() => {
    return Object.values(studentAnswers).filter(answer => {
        if (Array.isArray(answer)) return answer.length > 0; // 多选题
        return !!answer; // 其他题型
    }).length;
});

const unansweredCount = computed(() => totalQuestionCount.value - answeredCount.value);

// --- 方法 ---
/**
 * 根据题型标识符返回对应的中文名称
 * @param {string} type - 后端返回的题型标识符，例如 'single_choice'
 * @returns {string} - 对应的中文名称，例如 '单选题'
 */
const getQuestionTypeName = (type) => {
    // 定义一个映射表（map），存储英文标识符和中文名称的对应关系
    const map = {
        single_choice: '单选题',
        multi_choice: '多选题',
        true_false: '判断题',
        fill_blank: '填空题',
        matching: '匹配题',
        short_answer: '简答题',
        essay: '论述题',
        case_analysis: '案例分析题',
        practical: '实操题',
        file_upload: '文件上传题'
    };

    // 返回映射表中对应的值。如果找不到，则返回'未知题型'，防止页面显示空白或报错。
    return map[type] || '未知题型';
};
const getOptionLabel = (sequence) => String.fromCharCode(64 + sequence);

const confirmSubmit = () => {
    let message = "确认要提交答卷吗？提交后将无法修改。";
    if (unansweredCount.value > 0) {
        message += `<br/><strong style='color: red;'>注意：您还有 ${unansweredCount.value} 道题目未作答！</strong>`;
    }

    ElMessageBox.confirm(message, '交卷确认', {
        confirmButtonText: '确认提交',
        cancelButtonText: '继续作答',
        type: 'warning',
        dangerouslyUseHTMLString: true, // 允许在消息中使用 HTML
    }).then(() => {
        submitExam();
    }).catch(() => {
        ElMessage.info('已取消提交，请继续作答。');
    });
};

// const submitExam = async (isForced = false) => {
//     if (timerId) clearInterval(timerId);
//     isSubmitting.value = true;

//     const formattedAnswers = formatAnswersForSubmission();
//     const submissionData = {
//         examId: examId.value,
//         studentId: userStore.user.id, // 从 userStore 获取学生ID
//         submissionAnswers: formattedAnswers
//     };

//     // 调用我们新创建的、串联后的 action
//     examStore.submitAndGradeExam(submissionData, (gradeResponse) => {
//         isSubmitting.value = false;
//         ElMessage.success('答卷提交成功，客观题已自动批改！');

//         // 将返回的判分结果与原始题目列表合并，用于结果展示
//         const resultsMap = new Map(gradeResponse.map(ans => [ans.questionId, ans]));
//         submissionResult.value = questions.value.map(q => ({
//             ...q,
//             studentAnswer: resultsMap.get(q.examQuestion.id)
//         }));

//         isSubmitted.value = true; // 切换到结果展示状态
//     });
// };
const submitExam = async (isForced = false) => {
    if (timerId) clearInterval(timerId);
    isSubmitting.value = true;

    const formattedAnswers = formatAnswersForSubmission();
    const submissionData = {
        examId: examId.value,
        studentId: userStore.user.id, // 从 userStore 获取学生ID
        submissionAnswers: formattedAnswers
    };

    // 调用已更新的、串联了AI评分的 action
    examStore.submitAndGradeExam(submissionData, (allGradeResponses) => {
        isSubmitting.value = false;
        // 成功消息已在 action 内部处理

        // 将返回的包含AI反馈的完整评分结果与原始题目列表合并
        const resultsMap = new Map(allGradeResponses.map(ans => [ans.questionId, ans]));

        submissionResult.value = sortedQuestions.value.map(q => {
            const questionId = q.examQuestion.id;
            const studentAnswerAndFeedback = resultsMap.get(questionId);
            return {
                ...q,
                // studentAnswer 现在可能包含 feedback 字段
                studentAnswer: studentAnswerAndFeedback,
            };
        });

        isSubmitted.value = true; // 切换到结果展示状态
    }, (error) => {
        // 为失败场景添加处理
        isSubmitting.value = false;
        // 失败消息已在 action 内部处理
        console.error("提交或评分过程中发生错误:", error);
    });
};

const getScoreTagType = (answer, question) => {
    if (answer?.score === null || answer?.score === undefined) return 'info'; // 待批改
    if (answer.score >= question.points) return 'success'; // 满分
    if (answer.score > 0) return 'warning'; // 部分得分
    return 'danger'; // 0分
};

</script>

<style scoped>
.exam-container {
    background-color: #f0f2f5;
}

.exam-header {
    border: none;
    border-bottom: 1px solid #e0e0e0;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.exam-title h3 {
    margin-bottom: 0.5rem;
}

.exam-title p {
    color: #6c757d;
    font-size: 0.9rem;
    margin: 0;
}

.answer-sheet {
    width: 450px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
}

.answer-box {
    background-color: #f9f9f9;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #eee;
}

.answer-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 12px;
}

.answer-row:last-child {
    margin-bottom: 0;
}

.answer-tag {
    margin-right: 15px;
    flex-shrink: 0;
    width: 80px;
    /* 固定标签宽度以便对齐 */
    text-align: center;
}

.answer-content {
    line-height: 1.6;
}

.feedback-content {
    color: #e6a23c;
    /* 与 "AI评价" 标签颜色保持一致 */
    font-style: italic;
}

.sheet-title,
.sheet-progress {
    font-weight: bold;
    margin-bottom: 8px;
}

.sheet-numbers {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.sheet-number {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 30px;
    height: 30px;
    border: 1px solid #dcdfe6;
    border-radius: 50%;
    text-decoration: none;
    color: #606266;
    transition: all 0.2s;
}

.sheet-number:hover {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
}

.sheet-number.answered {
    background-color: var(--el-color-primary);
    color: #fff;
    border-color: var(--el-color-primary);
}

.question-list-container {
    max-width: 1200px;
    margin: 0 auto;
}

.question-card {
    margin-bottom: 20px;
}

/* 解决锚点跳转被顶部栏遮挡的问题 */
.question-card {
    scroll-margin-top: 150px;
}

.question-content {
    padding-left: 20px;
}

/* 在 <style scoped> 中添加 */
.description-content {
    line-height: 1.6;
    color: #606266;
}

.question-list-container {
    max-width: 1200px;
    margin: 0 auto;
    padding-top: 0;
    /* 调整上边距 */
}

.submit-footer {
    padding-bottom: 50px;
}
</style>